package clientSide;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

/*
 {
 data:
 {
 userName:
 }
 } 
 */
public class UserInfo {

	// user name
	private String user_name;

	public String getUserName() {
		return user_name;
	}

	public void setUserName(String name) {
		user_name = name;
	}

	// user display name
	private String display_name;

	public String getDisplayName() {
		return display_name;
	}

	// user email
	private String email;

	public String getEmail() {
		return email;
	}

	// user age
	private int age;

	public int getAge() {
		return age;
	}

	// user avatar link
	private String avatarUrl;

	public String ImageData() {
		return avatarUrl;
	}

	private List<Friend> friends;

	public List<Friend> getFriendList() {
		return friends;
	}

	public UserInfo(String User, String DislayName, String Email, int Age,
			String Avatar) {
		user_name = User;
		display_name = DislayName;
		email = Email;
		age = Age;
		avatarUrl = Avatar;
	}

	@SuppressWarnings("unchecked")
	public byte[] Serialize() throws IOException {
		JSONObject obj = new JSONObject();
		obj.put("USER", user_name);
		obj.put("DISPLAY", display_name);
		obj.put("EMAIL", email);
		obj.put("AGE", age);
		obj.put("AVATAR", avatarUrl);
		obj.put("FRIENDS", friends);
		StringWriter sw = new StringWriter();
		obj.writeJSONString(sw);
		return sw.toString().getBytes();
	}

	public static UserInfo readObject(byte[] data)
			throws ClassNotFoundException, IOException {
		Object o = new ObjectInputStream(new ByteArrayInputStream(data))
				.readObject();
		return (UserInfo) o;
	}

	public UserInfo(byte[] data) {
		try {
			String source = new String(data, "UTF-8");
			JSONParser parser = new JSONParser();
			JSONObject obj = (JSONObject) parser.parse(source);
			user_name = (String) obj.get("USER");
			display_name = (String) obj.get("DISPLAY");
			email = (String) obj.get("EMAIL");
			age = Integer.parseInt(obj.get("AGE").toString().trim());
			avatarUrl = (String) obj.get("AVATAR");
			JSONArray frs = (JSONArray) obj.get("FRIENDS");
			friends = new ArrayList<>();
			for (int i = 0; i < frs.size(); i++) {
				String s = frs.get(i).toString();
				JSONObject tmp = (JSONObject) new JSONParser().parse(s);
				friends.add(new Friend(tmp.get("CATALOG").toString(), tmp.get(
						"ID").toString(), tmp.get("DISPLAY").toString()));
			}
		} catch (UnsupportedEncodingException
				| org.json.simple.parser.ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
